package com.qkl.xiatang.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.dto.BusinessDTO;
import com.qkl.xiatang.app.dto.sale.BatchDetailDTO;
import com.qkl.xiatang.app.dto.sale.BatchWebDTO;
import com.qkl.xiatang.app.entity.pond.PondEntity;
import com.qkl.xiatang.app.entity.sale.SaleBatchDetailEntity;
import com.qkl.xiatang.app.entity.sale.SaleBatchEntity;
import com.qkl.xiatang.app.mapper.PondManagerMapper;
import com.qkl.xiatang.app.mapper.SaleBatchDetailMapper;
import com.qkl.xiatang.app.mapper.SaleBatchMapper;
import com.qkl.xiatang.app.utils.AppSessionUtils;
import com.qkl.xiatang.app.utils.AppUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class SaleService {

    @Autowired
    private SaleBatchMapper saleBatchMapper;

    @Autowired
    private SaleBatchDetailMapper saleBatchDetailMapper;

    @Autowired
    private PondManagerMapper pondManagerMapper;

    /**
     *增加销售批次
     * @param pondId
     * @return
     */
    public BusinessDTO<Object> addSaleBatch(String pondId){
        String companyId = AppSessionUtils.getCompanyId();
        List<PondEntity> pondList = pondManagerMapper.selectList(new QueryWrapper<PondEntity>().eq("company_id",companyId).eq("id",pondId));
        if(ObjectUtils.isEmpty(pondList)){
            return BusinessDTO.failBusiness("无此塘口");
        }
        QueryWrapper queryWrapper = new QueryWrapper<SaleBatchEntity>().eq("company_id",companyId).eq("pond_id",pondId).eq("status",0);
        if(ObjectUtils.isNotEmpty(saleBatchMapper.selectList(queryWrapper))){
            return BusinessDTO.failBusiness("存在销售批次未完成");
        }

        PondEntity pond = pondList.get(0);
        String id = AppUtils.genIdStr();
        SaleBatchEntity batchEntity = new SaleBatchEntity();
        batchEntity.setBatchNo(this.getBatchNo(companyId,pondId));
        batchEntity.setCreateTime(new Date());
        batchEntity.setSaleDate(AppUtils.todayYyyyMMdd());
        batchEntity.setCompanyId(companyId);
        batchEntity.setId(id);
        batchEntity.setMemo("");
        batchEntity.setPondId(pondId);
        batchEntity.setPondName(pond.getName());
        batchEntity.setSerialNo(pond.getSerialNo());
        batchEntity.setPrice(0.0);
        batchEntity.setTotalWeigh(0.0);
        batchEntity.setTotalPrice(0.0);
        batchEntity.setStatus(0);
        batchEntity.setUserId(AppSessionUtils.getUserId());
        batchEntity.setUserName(AppSessionUtils.getUserName());
        saleBatchMapper.insert(batchEntity);
        return BusinessDTO.sucessBusiness(batchEntity,"创建销售批次");
    }

    /**
     * 查询销售批次
     * @param pondId
     * @return
     */
    public BusinessDTO<Object> querySaleBatch(String pondId){
        String companyId = AppSessionUtils.getCompanyId();
        List<SaleBatchEntity> batchList = saleBatchMapper.selectList(new QueryWrapper<SaleBatchEntity>().eq("company_id",companyId).eq("pond_id",pondId).orderByDesc("create_time"));
        if(null == batchList){
            batchList = new ArrayList<>();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("batchList",batchList);
        return BusinessDTO.sucessBusiness(map,"查询销售批次");
    }

    /**
     * 保存批次明细
     * @param webdto
     * @return
     */
    public BusinessDTO<Object> saveSaleBatchDetail(BatchDetailDTO webdto){
        String batchId = webdto.getBatchId();
        String batchDetailId = webdto.getBatchDetailId();
        Double weigh = webdto.getWeigh();
        if(null == weigh || weigh <= 0.0){
           return BusinessDTO.failBusiness("重量格试不符");
        }
        if(StringUtils.isAllEmpty(batchId,batchDetailId)){
            return BusinessDTO.failBusiness("批次id及明细id不能全空");
        }
        String companyId = AppSessionUtils.getCompanyId();
        SaleBatchEntity querySaleBatch = null;
        if(StringUtils.isNotEmpty(batchId)){
            querySaleBatch = saleBatchMapper.selectById(batchId);
        }else {
            SaleBatchDetailEntity querySaleBatchDetail = saleBatchDetailMapper.selectById(batchDetailId);
            if(null != querySaleBatchDetail){
                querySaleBatch = saleBatchMapper.selectById(querySaleBatchDetail.getBatchId());
            }
        }
        if(null == querySaleBatch){
            return BusinessDTO.failBusiness("批次不存在");
        }
        if( !companyId.equals(querySaleBatch.getCompanyId())){
            return BusinessDTO.failBusiness("非公司销售");
        }
        if(querySaleBatch.isFinish()){
            return BusinessDTO.failBusiness("销售批次已完成");
        }

        if(StringUtils.isEmpty(batchDetailId)){
            batchDetailId = AppUtils.genIdStr();
            SaleBatchDetailEntity detailEntity = new SaleBatchDetailEntity();
            detailEntity.setBatchId(batchId);
            detailEntity.setPrice(0.0);
            detailEntity.setTotalPrice(0.0);
            detailEntity.setWeigh(weigh);
            detailEntity.setCreateTime(new Date());
            detailEntity.setId(batchDetailId);
            detailEntity.setUserId(AppSessionUtils.getUserId());
            detailEntity.setUserName(AppSessionUtils.getUserName());
            saleBatchDetailMapper.insert(detailEntity);
        }else {
            SaleBatchDetailEntity detailEntity = new SaleBatchDetailEntity();
            detailEntity.setId(batchDetailId);
            detailEntity.setWeigh(weigh);
            int  cnt = saleBatchDetailMapper.updateById(detailEntity);
            if(cnt < 1){
                return BusinessDTO.failBusiness("批次明细不存在");
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("batchDetail",saleBatchDetailMapper.selectById(batchDetailId));
        return BusinessDTO.sucessBusiness(map,"保存批次明细");
    }

    /**
     * 查询批次明细列表
     * @param batchId
     * @return
     */
    public BusinessDTO<Object> querySaleBatchDetailList(String batchId){
        //String companyId = AppSessionUtils.getCompanyId();
        QueryWrapper queryWrapper = new QueryWrapper<SaleBatchDetailEntity>().eq("batch_id", batchId).orderByDesc("create_time");
        List<SaleBatchDetailEntity> batchDetailList = saleBatchDetailMapper.selectList(queryWrapper);
        if(ObjectUtils.isEmpty(batchDetailList)){
            batchDetailList = new ArrayList<>();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("batchDetailList",batchDetailList);
        return BusinessDTO.sucessBusiness(map,"查询批次明细列表");
    }

    /**
     * 完成销售批次
     * @param webDTO
     * @return
     */
    @Transactional
    public BusinessDTO<Object> finishSaleBatch(BatchWebDTO webDTO){
        Double price = webDTO.getPrice();
        String batchId = webDTO.getBatchId();
        if(StringUtils.isEmpty(batchId)){
            return BusinessDTO.failBusiness("批次id不能为空");
        }
        if(null == price || price <= 0.0){
            return BusinessDTO.failBusiness("价格不合规范");
        }
        String companyId = AppSessionUtils.getCompanyId();
        SaleBatchEntity querySaleBatch = saleBatchMapper.selectById(batchId);
        if(null == querySaleBatch){
            return BusinessDTO.failBusiness("无此销售批次");
        }
        if( !companyId.equals(querySaleBatch.getCompanyId())){
            return BusinessDTO.failBusiness("非公司销售");
        }
        if(querySaleBatch.isFinish()){
            return BusinessDTO.failBusiness("销售批次已完成");
        }
        List<SaleBatchDetailEntity> detailList = saleBatchDetailMapper.selectList(new QueryWrapper<SaleBatchDetailEntity>().eq("batch_id",batchId));
        if(ObjectUtils.isEmpty(detailList)){
            return BusinessDTO.failBusiness("无批次明细");
        }
        Double batchTotalWeigh = 0.0;
        for(SaleBatchDetailEntity detailEntity : detailList){
            SaleBatchDetailEntity updEntity = new SaleBatchDetailEntity();
            updEntity.setId(detailEntity.getId());
            updEntity.setPrice(price);
            if(null != detailEntity.getWeigh()){
                batchTotalWeigh = AppUtils.addAmt(batchTotalWeigh,detailEntity.getWeigh());
                updEntity.setTotalPrice(AppUtils.multiplyAmt(price,detailEntity.getWeigh()));
            }
            saleBatchDetailMapper.updateById(updEntity);
        }
        SaleBatchEntity batchEntity = new SaleBatchEntity();
        batchEntity.setId(batchId);
        batchEntity.setTotalWeigh(batchTotalWeigh);
        batchEntity.setPrice(price);
        batchEntity.setTotalPrice(AppUtils.multiplyAmt(price,batchTotalWeigh));
        batchEntity.setStatus(1);
        saleBatchMapper.updateById(batchEntity);
        return BusinessDTO.sucessBusiness(saleBatchMapper.selectById(batchId),"完成销售批次");
    }

    /**
     * 删除销售批次
     * @param batchId
     * @return
     */
    public BusinessDTO<Object> deleteSaleBatch(String batchId){
        batchId = StringUtils.trimToEmpty(batchId);
        if(StringUtils.isEmpty(batchId)){
            return BusinessDTO.failBusiness("批次id不能为空");
        }
        String companyId = AppSessionUtils.getCompanyId();
        SaleBatchEntity querySaleBatch = saleBatchMapper.selectById(batchId);
        if(null == querySaleBatch){
            return BusinessDTO.failBusiness("无此销售批次");
        }
        if( !companyId.equals(querySaleBatch.getCompanyId())){
            return BusinessDTO.failBusiness("非公司销售");
        }
        if(querySaleBatch.isFinish()){
            return BusinessDTO.failBusiness("销售批次已完成,不能删除");
        }
        //gt >,ge  >= ,lt < ,le <=
        QueryWrapper queryWrapper = new QueryWrapper<SaleBatchDetailEntity>().eq("batch_id",batchId).isNotNull("weigh").gt("weigh",0.0);
        List<SaleBatchDetailEntity> detailList = saleBatchDetailMapper.selectList(queryWrapper);
        if(ObjectUtils.isNotEmpty(detailList)){
            return BusinessDTO.failBusiness("销售批次已存在明细,不能删除");
        }
        saleBatchDetailMapper.delete(new QueryWrapper<SaleBatchDetailEntity>().eq("batch_id",batchId));
        saleBatchMapper.deleteById(batchId);
        Map<String,String> map = new HashMap<>();
        map.put("batchId",batchId);
        return BusinessDTO.sucessBusiness(map,"删除销售批次");
    }

    /**
     * 删除销售批次明细
     * @param batchDetailId
     * @return
     */
    public BusinessDTO<Object> deleteSaleBatchDetail(String batchDetailId){
        batchDetailId = StringUtils.trimToEmpty(batchDetailId);
        if(StringUtils.isEmpty(batchDetailId)){
            return BusinessDTO.failBusiness("批次明细id不能为空");
        }
        String companyId = AppSessionUtils.getCompanyId();
        SaleBatchDetailEntity detailEntity = saleBatchDetailMapper.selectById(batchDetailId);
        if(null == detailEntity){
            return BusinessDTO.failBusiness("无此销售批次明细");
        }
        SaleBatchEntity querySaleBatch = saleBatchMapper.selectById(detailEntity.getBatchId());
        if(null == querySaleBatch){
            return BusinessDTO.failBusiness("无此销售批次");
        }
        if( !companyId.equals(querySaleBatch.getCompanyId())){
            return BusinessDTO.failBusiness("非公司销售");
        }
        if(querySaleBatch.isFinish()){
            return BusinessDTO.failBusiness("销售批次已完成,不能删除明细");
        }
        saleBatchDetailMapper.deleteById(batchDetailId);
        Map<String,String> map = new HashMap<>();
        map.put("batchDetailId",batchDetailId);
        return BusinessDTO.sucessBusiness(map,"删除销售批次明细");
    }

    private int getBatchNo(String companyId,String pondId){
        QueryWrapper queryWrapper = new QueryWrapper<SaleBatchEntity>().eq("company_id",companyId).eq("pond_id",pondId).eq("status",1).orderByDesc("batch_no").last("LIMIT 1");
        SaleBatchEntity entity = saleBatchMapper.selectOne(queryWrapper);
        int batchNo = 1;
        if(null != entity){
            batchNo = entity.getBatchNo() + 1;
        }
        return batchNo;
    }

}
